import axios from 'axios'
import { MessageBox, Message, Loading  } from 'element-ui'
//前端 blob数据存储库
import { saveAs } from 'file-saver';
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 500000 // request timeout
})

// 请求这前的拦截器，请求头中存放令牌，get请求进行能数转换
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      config.headers['satoken'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
     //判断返回数据类型是不是blob,如果是直接放行
      if(response.request.responseType ===  'blob' || response.request.responseType ===  'arraybuffer'){
          return response.data
       }


    const res = response.data

    // if the custom code is not 200, it is judged as an error.
    if (res.code !== 200) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 619: 令牌为空; 614: 令牌过期; 611: 令牌错误;
      if (res.code === 619 || res.code === 614 || res.code === 611) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service



//自定义文件下载工具
let downloadLoadingInstance;
// 通用下载方法
export function download(url, data, filename,config) {
  downloadLoadingInstance = Loading.service({ text: "正在下载数据，请稍候", background: "rgba(0, 0, 0, 0.7)", })

  //创建一个post的ajax请求
  return service.post(url, data, {
    responseType: 'blob',
    ...config
  }).then(async (resp) => {
    //判断返回结果是不是一个二进制文件
    const isBlob = await blobValidate(resp);
    if (isBlob) {
      const blob = new Blob([resp])
      saveAs(blob, filename)
    } else {
      const resText = await resp.text();
      const rspObj = JSON.parse(resText);
      const errMsg =  rspObj.msg
      Message({message: errMsg ,type: 'error',duration: 5 * 1000})
    }
    downloadLoadingInstance.close();
  }).catch((r) => {
    console.log(r)
    Message({message: '下载文件出现错误，请联系管理员！' ,type: 'error',duration: 5 * 1000})
    downloadLoadingInstance.close();
  })
}

// 验证是否为blob格式
async function blobValidate(data) {
  try {
    const text = await data.text();
    //数据尝试转换成json对象
    JSON.parse(text);
    return false;
  } catch (error) {
    return true;
  }
}
